package cn.kimming.rpc.demo.lb;

import cn.kimming.rpc.demo.lb.service.LoadBalanceService;
import cn.kimming.rpc.remoting.registry.InstanceDetail;
import cn.kimming.rpc.remoting.registry.ServerRpcRegistry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Collection;

@SpringBootApplication
public class LBApplication {
    public static void main(String[] args) {
        SpringApplication.run(LBApplication.class, args);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("卸载" + LoadBalanceService.class.getCanonicalName() + "所有服务实例");
                ServiceDiscovery<InstanceDetail> discovery = ServerRpcRegistry.getDiscovery();
                try {
                    Collection<ServiceInstance<InstanceDetail>> serviceInstances = discovery.queryForInstances(LoadBalanceService.class.getCanonicalName());
                    for (ServiceInstance<InstanceDetail> serviceInstance : serviceInstances) {
                        discovery.unregisterService(serviceInstance);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
